package top.jacktgq.web.struts2;

import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.io.IOUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.multipart.MultiPartRequestWrapper;
import top.jacktgq.dao.StudentDao;
import top.jacktgq.pojo.Student;
import top.jacktgq.utils.MapperUtils;

import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.HashMap;

/**
 * @Author CandyWall
 * @Date 2021/6/20--12:34
 * @Description
 */
public class AddStudentAction extends ActionSupport {
    public void addStudent() {
        HashMap resultMap = new HashMap();
        String msg = "保存成功";

        MultiPartRequestWrapper request = (MultiPartRequestWrapper) ServletActionContext.getRequest();
        HttpServletResponse response = ServletActionContext.getResponse();
        Student student = new Student();
        student.setStu_id(request.getParameter("stu_id"));
        student.setName(request.getParameter("name"));
        student.setEmail(request.getParameter("email"));
        try {
            student.setBirthdate(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("birthdate")));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        student.setAge(Integer.parseInt(request.getParameter("age")));
        student.setSex(Integer.parseInt(request.getParameter("sex")));
        student.setPhone(request.getParameter("phone"));
        student.setPhoto_base64(request.getParameter("photo_base64"));
        System.out.println(student);
        try {
            InputStream in = new FileInputStream(request.getFiles("photo")[0]);// 获得上传文件字节流
            // 使用IOUtils工具输出， 也就是copy文件
//                        IOUtils.copy(in, out);
            byte[] bytes = IOUtils.toByteArray(in);
            student.setPhoto_byte(bytes);
            StudentDao studentService = new StudentDao();
            studentService.addStudent(student);
        } catch (Exception e) {
            e.printStackTrace();
            msg = "保存失败！";
        }

        resultMap.put("code", 0);
        resultMap.put("msg", msg);
        try {
            response.getWriter().write(MapperUtils.mapToJson(resultMap));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
